Passed
Push — master ( d29869...e61a0d )
by Joe Nilson
03:35
created

CommonDomFunctions.js ➔ purchasesNCFVerify   B

Complexity

Conditions 7

Size

Total Lines 51
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 40
dl 0
loc 51
rs 7.52
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/*
2
 * Copyright (C) 2021 Joe Nilson <[email protected]>
3
 *
4
 * This program is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as
6
 * published by the Free Software Foundation, either version 3 of the
7
 * License, or (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 * You should have received a copy of the GNU Lesser General Public License
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
 */
16
17
/**
18
 * @param {string} tipoComprobante
19
 * @returns {Promise<*>}
20
 */
21
async function verificarCorrelativoNCF(tipoComprobante, tipoOperacion)
22
{
23
    let pagina = (tipoOperacion === 'Venta') ? 'EditFacturaCliente' : 'EditFacturaProveedor';
24
    let ArrayTipoNCFCompras = ['11','12','16','17'];
25
    if (tipoOperacion === 'Compra' && !ArrayTipoNCFCompras.includes(tipoComprobante)) {
26
        return true;
27
    }
28
    var now = new Date();
29
    let ncfDueDate = now.getFullYear()+'-12-31';
30
    logConsole(tipoComprobante, 'tipoComprobante');
31
    logConsole(ncfDueDate, 'ncfDueDate');
32
    return $.ajax({
33
        url: pagina,
34
        async: true,
35
        data: {'action': 'busca_correlativo', 'tipocomprobante': tipoComprobante },
36
        type: 'POST',
37
        datatype: 'json',
38
        success: function (response) {
39
            let data = JSON.parse(response);
40
            if ( data.existe === false ) {
41
                executeModal(
42
                    'verificaNCF',
43
                    'No hay Correlativo de NCF Disponible',
44
                    'No hay correlativos disponibles para el Tipo de NCF ' +
45
                    tipoComprobante + ' <br/>Por favor revise su maestro de NCFs',
46
                    'warning'
47
                );
48
            }
49
            if (tipoComprobante !== '02') {
50
                $("input[name='ncffechavencimiento']").val(ncfDueDate);
51
                $("input[name='ncffechavencimiento']").focus();
52
            }
53
        },
54
        failure: function (response) {
55
            alert('Ha ocurrido algún tipo de falla ' + response);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
56
        },
57
        error: function (xhr, status) {
58
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
59
        }
60
    });
61
}
62
63
async function actualizarInformacionParaNCF()
64
{
65
    var infoCliente = await cargarInfoCliente();
66
    logConsole(infoCliente, 'infoCliente');
67
    var datosCliente = JSON.parse(infoCliente);
0 ignored issues
show
Unused Code introduced by
The variable datosCliente seems to be never used. Consider removing it.
Loading history...
68
    var tipoPago = await cargarTipoPago();
69
    var datosPago = JSON.parse(tipoPago);
0 ignored issues
show
Unused Code introduced by
The variable datosPago seems to be never used. Consider removing it.
Loading history...
70
    var tipoNCFs = await cargarTipoNCF('Ventas');
71
    logConsole(tipoNCFs, 'tipoNCFs');
72
    var datosTipoNCFs = JSON.parse(tipoNCFs);
0 ignored issues
show
Unused Code introduced by
The variable datosTipoNCFs seems to be never used. Consider removing it.
Loading history...
73
    let selectTiposNCF = "";
0 ignored issues
show
Unused Code introduced by
The variable selectTiposNCF seems to be never used. Consider removing it.
Loading history...
74
    var descInfoClienteTipoComprobante = '';
0 ignored issues
show
Unused Code introduced by
The variable descInfoClienteTipoComprobante seems to be never used. Consider removing it.
Loading history...
75
    var tipoMovimiento = await cargarTipoMovimiento();
76
    var datosMovimiento = JSON.parse(tipoMovimiento);
0 ignored issues
show
Unused Code introduced by
The variable datosMovimiento seems to be never used. Consider removing it.
Loading history...
77
78
}
79
80
/**
81
 * logConsole in Debug mode
82
 * @param  {string|Object|boolean} value
83
 * @param {string} description
84
 */
85
function logConsole(value, description ='data')
86
{
87
    if ($(".debugbar") !== undefined) {
88
        console.log(description, value);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
89
    }
90
}
91
92
/********
93
 * Util Functions
94
 */
95
function isBusinessDocumentPage()
96
{
97
    let businessDocument = '';
98
    if ($('#purchaseFormHeader').length > 0) {
99
        businessDocument = 'Compra';
100
    } else if ($('#salesFormHeader').length > 0) {
101
        businessDocument = 'Venta';
102
    }
103
    return businessDocument;
104
}
105
106
async function cargarTipoNCF(businessDocument, tipoOperacion)
107
{
108
    let pagina = (businessDocument === 'Venta') ? 'EditFacturaCliente' : 'EditFacturaProveedor';
109
    return $.ajax({
110
        url: pagina,
111
        async: true,
112
        data: {'action': 'busca_tipo', 'tipodocumento': tipoOperacion.toLowerCase() },
113
        type: 'POST',
114
        datatype: 'json',
115
        success: function (response) {
116
            let data = JSON.parse(response);
117
            return data;
118
        },
119
        error: function (xhr, status) {
120
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
121
        }
122
    });
123
}
124
125
async function cargarInfoCliente()
126
{
127
    return $.ajax({
128
        url: 'EdifFacturaCliente',
129
        async: true,
130
        data: {'action': 'busca_infocliente', 'codcliente': $("input[name=codcliente]").val()},
131
        type: 'POST',
132
        datatype: 'json',
133
        success: function (response) {
134
            let data = JSON.parse(response);
135
            return data;
136
        },
137
        error: function (xhr, status) {
138
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
139
        }
140
    });
141
}
142
143
async function cargarTipoPago(businessDocument)
144
{
145
    let pagina = (businessDocument === 'Venta') ? 'EditFacturaCliente' : 'EditFacturaProveedor';
146
    let tipoPago = (businessDocument === 'Venta') ? '01' : '02';
147
    return $.ajax({
148
        url: pagina,
149
        async: true,
150
        data: {'action': 'busca_pago', 'tipopago': tipoPago},
151
        type: 'POST',
152
        datatype: 'json',
153
        success: function (response) {
154
            let data = JSON.parse(response);
155
            return data;
156
        },
157
        error: function (xhr, status) {
158
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
159
        }
160
    });
161
}
162
163
async function purchasesNCFVerify()
164
{
165
    let ncf = $("input[name='numeroncf']").val();
166
    logConsole(ncf, 'NCF');
167
    let proveedor = $("input[name='codproveedor']").val();
168
    let now = new Date();
169
    let ncfDueDate = now.getFullYear()+'-12-31';
170
    if (proveedor === '' || ncf === '') {
171
        executeModal(
172
            'proveedorOrNcfEmpty',
173
            'Complete los datos',
174
            'Seleccione un Proveedor y un NCF para validar el documento',
175
            'warning'
176
        );
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
177
    } else {
178
        return $.ajax({
179
            url: 'EditFacturaProveedor',
180
            async: true,
181
            data: {'action': 'verifica_documento', 'ncf': ncf, 'proveedor': proveedor},
182
            type: 'POST',
183
            datatype: 'json',
184
            success: function (response) {
185
                let data = JSON.parse(response);
186
                if (data.success) {
187
                    $("#btnVerifyNCF").attr('class', '').addClass("btn btn-success btn-spin-action");
188
                    $("#iconBtnVerify").attr('class', '').addClass("fas fa-check-circle fa-fw");
189
                    var formNumProveedorType = ncf.slice(-10, -8);
190
                    $("select[name='tipocomprobante']").val(formNumProveedorType);
191
                    if (formNumProveedorType !== '02') {
192
                        $("input[name='ncffechavencimiento']").val(ncfDueDate);
193
                        $("input[name='ncffechavencimiento']").focus();
194
                    }
195
                }
196
                if (data.error) {
197
                    $("#btnVerifyNCF").attr('class', '').addClass("btn btn-danger btn-spin-action");
198
                    $("#iconBtnVerify").attr('class', '').addClass("fas fa-exclamation-circle fa-fw");
199
                    executeModal(
200
                        'ncfExists',
201
                        'NCF Ya registrado',
202
                        'el NCF ya ha sido registrado con la '+data.message,
203
                        'warning'
204
                    );
205
                }
206
                return data;
207
            },
208
            error: function (xhr, status) {
209
                alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
210
            }
211
        });
212
    }
213
}
214
215
async function cargarTipoMovimiento(businessDocument)
216
{
217
    let pagina = (businessDocument === 'Venta') ? 'EditFacturaCliente' : 'EditFacturaProveedor';
218
    let tipoMovimiento = (businessDocument === 'Venta') ? 'VEN' : 'COM';
219
    return $.ajax({
220
        url: pagina,
221
        async: true,
222
        data: {'action': 'busca_movimiento', 'tipomovimiento': tipoMovimiento},
223
        type: 'POST',
224
        datatype: 'json',
225
        success: function (response) {
226
            let data = JSON.parse(response);
227
            return data;
228
        },
229
        error: function (xhr, status) {
230
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
231
        }
232
    });
233
}
234
235
$(document).ready(function () {
236
    logConsole($("input[name=codcliente]").val(), 'codcliente');
237
    let tipoOperacion = isBusinessDocumentPage();
238
    let varNCFTipoComprobante = $("select[name='tipocomprobante']");
239
    logConsole($("select[name='tipocomprobante']").val(), 'tipocomprobante');
240
    if (varNCFTipoComprobante.length !== 0 && varNCFTipoComprobante.val() !== '' && tipoOperacion !== '') {
241
        verificarCorrelativoNCF($("select[name='tipocomprobante']").val(), tipoOperacion);
242
    }
243
244
    $("#findCustomerModal").on('hidden.bs.modal', function () {
245
        setTimeout(function () {
246
            let varNCFTipoComprobante = $("select[name='tipocomprobante']");
247
            logConsole($("input[name=codcliente]").val(), 'codcliente 2');
248
            logConsole(varNCFTipoComprobante.val(), 'tipocomprobante 2');
249
            logConsole(tipoOperacion, 'tipoOperacion 2');
250
            if (varNCFTipoComprobante.length !== 0 && varNCFTipoComprobante.val() !== '' && tipoOperacion !== '') {
251
                verificarCorrelativoNCF($("select[name='tipocomprobante']").val(), tipoOperacion);
252
            }
253
        },300);
254
    });
255
256
    varNCFTipoComprobante.change(function () {
257
        logConsole(varNCFTipoComprobante.val(),"tipocomprobante val");
258
        if (tipoOperacion !== '') {
259
            verificarCorrelativoNCF(varNCFTipoComprobante.val(), tipoOperacion);
260
        }
261
    });
262
});